package cn.sunzhichao.service.impl;

import cn.sunzhichao.mapper.CommentMapper;
import cn.sunzhichao.pojo.Comment;
import cn.sunzhichao.service.CommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        List<Comment> comments = commentMapper.selectList(new QueryWrapper<Comment>().eq("blog_id", blogId).orderByAsc("create_time"));
        return firstComment(comments);
    }

    @Override
    public int saveComment(Comment comment, String avatar) {
        comment.setCreateTime(LocalDateTime.now());
        comment.setAvatar(avatar);
        return commentMapper.insert(comment);
    }

    public List<Comment> firstComment(List<Comment> comments) {

        ArrayList<Comment> list = new ArrayList<>();
        for (Comment comment : comments) {
            if(comment.getParentCommentId() < 0) {
                comment.setReplyComments(findReply(comments, comment.getId()));
                list.add(comment);
            }
        }
        return list;
    }

    /**
     *
     * @param comments 所有评论
     * @param targetId 一个顶层评论
     * @return  返回父亲为targetId的所有comment的集合
     */
    private List<Comment> findReply(List<Comment> comments, Long targetId) {

        List<Comment> reply = new ArrayList<>();
        for(Comment comment : comments) {
            if((getParentId(comment.getId()) == targetId) && (comment.getId() != targetId)) {
                reply.add(comment);
            }
        }
        return reply;
    }

    /**
     * 返回id的父亲id
     * @param id
     * @return
     */
    private Long getParentId(Long id) {
        Long parentId = commentMapper.selectById(id).getParentCommentId();
        if(parentId < 0) {
            return id;
        } else {
            return getParentId(parentId);
        }
    }
}
